package servlet;

import dao.BlogDao;
import dao.UserDao;
import model.Blog;
import model.User;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/count")
public class CountServlet extends HttpServlet {
    public BlogDao blogDao = new BlogDao();
    public UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //博客列表页，返回登录用户博客数
        //登录用户信息，从seesion里面去拿
        //博客详情页，返回作者的博客数
        //作者的信息，根据blogId去查
        resp.setCharacterEncoding("utf-8");
        //获取用户登录信息
        HttpSession session = req.getSession(false);
        if(session == null || session.getAttribute("user") == null){
            resp.getWriter().write("用户未登录");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null || user.getId() <= 0){
            resp.getWriter().write("用户未登录");
            return;
        }
        String blogIdParam = req.getParameter("blogId");
        //博客列表页
        if(blogIdParam == null || "".equals(blogIdParam)){
            //返回用户登录的博客数
            Integer userid = user.getId();
            Integer count = blogDao.numBolgById(userid);
            resp.setContentType("application/json;");
//            System.out.println(count);
            resp.getWriter().write(JSONUtil.toJson(count));
        }else{
            //博客详情页
            Integer blogId = Integer.parseInt(blogIdParam);
            Blog blog = blogDao.selectById(blogId);
            //拿到作者信息
            User author = userDao.selectById(blog.getUserId());

            //判断当前登录用户是否和作者是同一个人
            if(author.getId().equals(user.getId())){
                author.setIsYourBlog(1);
            }
            //返回作者博客数
            Integer authorid = author.getId();
            Integer count = blogDao.numBolgById(authorid);
//            System.out.println(count);
            resp.setContentType("application/json;");
            resp.getWriter().write(JSONUtil.toJson(count));
        }
    }
}
